from rest_framework import serializers
from books.models import BookInfo, HeroInfo


# 英雄序列化器

class HeroSerialzier(serializers.Serializer):
    hname = serializers.CharField()
    hcomment = serializers.CharField()

    # id = serializers.IntegerField(label='ID', read_only=True)
    # hbook = serializers.PrimaryKeyRelatedField(label='图书', read_only=True)
    # hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)


    def create(self, validated_data):
        hero = HeroInfo.objects.create(**validated_data)
        return hero
#------------------------------------------------------------------------------
# 创建图书序列化器
class BooksSerialzier(serializers.Serializer):
    # 序列化
    # btitle = serializers.CharField(max_length=20, min_length=5, write_only=True)# require = true 必须做反序列化输入的字段
    btitle = serializers.CharField(max_length=20, min_length=3)
    bpub_date = serializers.DateField()
    bread = serializers.IntegerField(min_value=5, max_value=20)
    bcomment = serializers.IntegerField(default=5)
    # password=serializers.CharField(write_only=True) write——only参与反序列化，只接受和验证，不参与返回，而read_only不参与验证，
    # 只做序列化输出
    # 返回关联英雄id值
    # heroinfo_set=serializers.PrimaryKeyRelatedField(read_only=True,many=True)
    # 返回关联英雄模型类中str方法返回的值
    # heroinfo_set=serializers.StringRelatedField(read_only=True,many=True)

    # heroinfo_set = HeroSerialzier(many=True)
#---------------
# class HeroSerialzier(serializers.Serializer):
#     hname = serializers.CharField()
#     hcomment = serializers.CharField()
#
#     # hbook=serializers.PrimaryKeyRelatedField(read_only=True)
#     # hbook=serializers.StringRelatedField()#查询所有的英雄关联的书，
#     hbook = BooksSerialzier() 当仅当定义一个序列化器对象来
    '''
    [
  {
    "hname": "郭靖",
    "hcomment": "降龙十八掌",
    "hbook": {
      "btitle": "射雄传",
      "bpub_date": "2010-05-11",
      "bread": 12,
      "bcomment": 34
    }
  ....
    '''
#-----------------------------------------------------------------------
    #

    # 单一字段的方法验证
    def validate_btitle(self, value):

        if value == 'python':
            raise serializers.ValidationError('书名不能是python')

        return value

    # 多个字段验证
    def validate(self, attrs):

        if attrs['bread'] < attrs['bcomment']:
            raise serializers.ValidationError('阅读量小于评论量')

        return attrs
    #
    def create(self, validated_data):
        book = BookInfo.objects.create(**validated_data)
        return book
    # # def create(self, validated_data):
    # #     hero = HeroInfo.objects.create(**validated_data)
    # #     return hero
    # #修改属性
    def update(self, instance, validated_data):
        instance.bread = validated_data['bread']
        instance.btitle = validated_data['btitle']
        instance.bcomment = validated_data['bcomment']
        instance.bpub_date = validated_data['bpub_date']
        instance.save()
        return instance

#------------------------------------------------------
"""
逻辑:instance代表的是实例属性,data代表的是类方法,数据是靠instance接受,proprety 是把方法当成属性调用
实际思路和模型类属性的修改的原理一样,序列化1,接受要修改的数据,传递要修改的对象,以要修改的对象传给instance ,以修改的数据
传给data 验证data提取字段是否合法,创建修改的方法,update()---当instance是空,就会调用Create 如果有数据就只做修改操作
data 接受的是前端修改的数据,instance 表示原始数据的对象,还是采用赋值的方式



"""


#
# #--------------------------
# class BookModelSerializer(serializers.ModelSerializer):
#     # 显示指明修改字段选项内容
#     bread=serializers.IntegerField(max_value=20,min_value=10)
#     class Meta:
#         model = BookInfo # 指定根据那个模型类生成字段
#         fields='__all__'  # 指定生成哪些字段
#         # exclude=('btitle',) # 取反生成字段
#         read_only_fields=('bpub_date',) # 给字段指定read_only选项参数
#         # 添加修改字段选项参数
#         extra_kwargs={
#             'bcomment':{
#                 'read_only':True
#             }
#
#         }
#

